#include "..\ProcessHistory\MainFrm.h"
#include "wtl\wtl.h"
#include <atlctrls.h>
#include "boost/date_time/posix_time/posix_time.hpp"
#include "PH.h"
#include "screen.h"
#include "query.h"
#include "..\ProcessHistory\PHScroll.h"
#include <boost/thread/thread.hpp>

using namespace boost::posix_time;
using namespace boost;
using namespace std;

extern PH ph_instance;
extern PHDisplay phd;
extern PHQuery phq;
extern mutex work_mtx;

void Worker();

void CMainFrame::DateTimeQry()
{	
		char q[100];
		int ql=m_Combo.GetWindowTextLength();
		m_Combo.GetWindowText(q,ql+1);
		/*catch exceptions thrown by boost*/
		ptime Begin;
		string s=string(q);//+".000";
		try 
		{			
			Begin=time_from_string(s);
		}
		catch(boost::exception &)
		{
			::SetWindowText(ph_instance._hWndStatusBar,"Input not in YYYY-MM-DD HH:MM:SS format.");
			return ;
		}

		if(Begin.is_not_a_date_time() )
		{
			::SetWindowText(ph_instance._hWndStatusBar,"Input not in YYYY-MM-DD HH:MM:SS format.");
			return ;
		}

		RECT r;
	::GetWindowRect(m_hWnd,&r);
	m_wndHorzSplit.SetSplitterPos ((int)(((float)r.bottom/10)*7.5));
string SQL=phq.Construct(Begin);

		/*Query the data*/
		phq.SetSQL(SQL);
		thread st(&Worker);
}
void Worker()
{
	//mutex::scoped_lock work_sl(work_mtx);
	//work_mtx.lock();
	::SetWindowText(ph_instance._hWndStatusBar,"Working...");
	phd._complete=false;
	if(phq.Query()==0)			
	{
		::SetWindowText(ph_instance._hWndStatusBar,"No results. Try a broader search by year/month/day.");
		work_mtx.unlock();
	}
	else
	{
			/*set the display*/
		phd.UpdateWindow();
		phd._complete=true;
		::PostMessage (ph_instance._hWnd, UWM_DOWNLOAD_PROGRESS, 0, 0 );
	  // Remove the progress bar from the taskbar button.
/*        if ( m_pTaskbarList )
            m_pTaskbarList->SetProgressState ( ph_instance._hWnd, TBPF_NOPROGRESS );*/
			//return true;
	}
	//phd._complete=true;
}

LRESULT CMainFrame:: NotifyGUI (UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	SIZE s;
	s.cx=0;//phd._Width;
	s.cy=41*(phq._lCount+1)+50;
			
	phs.SetSize(s);
	phs.Invalidate();
	phti.Invalidate();

	//SIZE s;
		//s.cx=0;//phd._Width;
		//s.cy=41*(phq._lCount+1)+50;
		//phs.SetSize(s);
		
	if(wParam==1)
	{
	string dt;
		dt=to_iso_extended_string(phd._WinLeft);
		dt.replace(10,1," ");
		//remove seconds
		m_Combo.SetWindowText(dt.substr(0,dt.length()-3).c_str());
	}
		//phs.Invalidate();
		//phti.Invalidate();
	work_mtx.unlock();
	return 0;
}